package server;

import spread.AdvancedMessageListener;
import spread.SpreadException;
import spread.SpreadMessage;

public class AdvancedSpreadListener implements AdvancedMessageListener {

	private ClusterManagementModule CMM;
	
	public AdvancedSpreadListener(ClusterManagementModule CMM){
		this.CMM = CMM;
	}
	
	public void membershipMessageReceived(SpreadMessage message) {
		// TODO Write AdvancedSpreadListener.membershipMessageReceived()

	}

	public void regularMessageReceived(SpreadMessage message) {
		// TODO Write AdvancedSpreadListener.regularMessageReceived()

		try {
			// Get the cluster message from the spread message
			ClusterMessage ClusterMSG = (ClusterMessage)message.getObject();
			
			// Interpret the type of the message
			switch(ClusterMSG.getType()){
				case NEW_TASK :
				{
					// Convert the message to a "New Task" message object
					ClusterMessage_NewTask msg = (ClusterMessage_NewTask)ClusterMSG;
					// Inform the CMM of a "New Task" message
					CMM.RecieveNewTask(msg.getSenderID(), msg.getTaskContext());
					break;
				}
				case UPDATE_TASK :
				{
					// Convert the message to a "Update Task" message object
					ClusterMessage_UpdateTask msg = (ClusterMessage_UpdateTask)ClusterMSG;
					// Inform the CMM of an "Update Task" message
					CMM.RecieveUpdateTask(msg.getSenderID(), msg.getTaskID(), msg.getContextUpdate());
					break;
				}
				case TERMINATE_TASK :
				{
					// Convert the message to a "Terminate Task" message object
					ClusterMessage_TerminateTask msg = (ClusterMessage_TerminateTask)ClusterMSG;
					// Inform the CMM of an "Terminate Task" message
					CMM.RecieveTerminateTask(msg.getSenderID(), msg.getTaskID());
					break;
				}
				case NEW_SERVER_READY :
				{
					// Convert the message to a "New Server Ready" message object
					ClusterMessage_NewServerReady msg = (ClusterMessage_NewServerReady)ClusterMSG;
					// Inform the CMM of an "Terminate Task" message
					CMM.RecieveNewServerReady(msg.getSenderID());
					break;
				}
				default:
					// Inform the CMM that an unsupported message was recieved
					CMM.RecieveUnsupportedMessage();
			}
			
		} catch (SpreadException e) {
			// TODO handle exception
			e.printStackTrace();
		}
	
	}

}
